C     Estimate the wall temperatures by solving the heat flux
C     equations, invoked subroutine hybrd1 developed by the 
C     University of Chicago, as Operator of Argonne National 
C     Laboratory and downloaded from http://www.netlib.org/minpack
C     Tube-side equation:  
C     H1*(T1-TW1) = C*(PV(TW1)-PV(TW2))*dH(TW1)+KM/THICK*(TW1-TW2)
C     Shell-side equation:
C     H2*(TW2-T2) = C*(PV(TW1)-PV(TW2))*dH(TW2)+KM/THICK*(TW1-TW2)
      SUBROUTINE DCMD_ESTW(T, H, TW, IFLAG)
      USE DCMD_CMOD
C     T - (input) bulk temperatures in tube side and shell side [K]
C     H - (input) heat transfer film coefficients of tube side and
C                 shell side [W/m2-s]
C     TW - (output) wall temperatures of tube side and shell side [K]
C     IFLAG - (output) running status
      REAL*8 T(2), H(2), TW(2)
      INTEGER*4 IFLAG
C     Arguments for non-linear equations solver
      INTEGER*4 N, LWA, INFO
      PARAMETER (N = 2)
      PARAMETER (LWA = N*(3*N+13)/2)
      REAL*8 X(N), FVEC(N), TOL, WA(LWA)
      EXTERNAL FCN
      
      TOL = 1.D-5
      
C     Initial values
      DO I = 1, 2
        X(I) = T(I)
      END DO
C     Pass arguments to common module
      DO I = 1, 2
C       COM_TLOC(I) = T(I) ! COM_TLOC has already given in dcmd_solv
        COM_HLOC(I) = H(I)
      END DO
      
      CALL HYBRD1(FCN, N, X, FVEC, TOL, INFO, WA, LWA)      
      
      DO I = 1, 2
        TW(I) = X(I)
      END DO
      IFLAG = INFO
      
      RETURN
      
      END SUBROUTINE DCMD_ESTW

C     ***************************************************************     
      SUBROUTINE FCN(N, TW, FVEC, IFLAG)
C     Common variables declaration
      USE DCMD_CMOD
C     Arguments of subroutine
      INTEGER N, IFLAG
      DOUBLE PRECISION TW(N), FVEC(N)
C     Process variables
      REAL*8 T(2), H(2), JM, JHC, JHV(2)
      INTEGER I
C     Membrane properties
      REAL*8 KM, CM, THK
C     User functions
      REAL*8 SVP, DHVAP

C     Retrieve membrane properties from common module
      CM = COM_PERM
      KM = COM_COND
      THK = COM_THK
C     Retrieve process variables from common module
      DO I = 1, 2
        T(I) = COM_TLOC(I)
        H(I) = COM_HLOC(I)
      END DO
      
      JM = CM*(SVP(TW(1))-SVP(TW(2)))
      JHC = KM/THK*(TW(1)-TW(2))
      DO I = 1, 2
        JHV(I) = JM*DHVAP(TW(I))
      END DO      
      FVEC(1) = H(1)*(T(1)-TW(1))-JHV(1)-JHC
      FVEC(2) = H(2)*(TW(2)-T(2))-JHV(2)-JHC
      
      RETURN
      
      END SUBROUTINE FCN